import paramiko
from scp import SCPClient

# 跳板机配置
jump_host = '192.168.100.227'
jump_user = 'u'
jump_password = '1'

# 太空服务器配置
target_host = '192.168.201.103'
target_user = 'user'
target_password = 'user'

# 本地文件路径和目标路径
local_model_path = './Model/ModelAPI'
remote_target_path = '/home/user/experiment/16/work/'

# 通过跳板机连接目标服务器并传输文件
def transfer_file_via_jump_host():
    # 创建跳板机 SSH 客户端
    jump_client = paramiko.SSHClient()
    jump_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自动接受未知的主机密钥
    jump_client.connect(jump_host, username=jump_user, password=jump_password)

    # 使用跳板机建立代理连接到目标服务器
    jump_transport = jump_client.get_transport()
    dest_addr = (target_host, 22)
    jump_channel = jump_transport.open_channel('direct-tcpip', dest_addr, (jump_host, 22))

    # 创建目标服务器的 SSH 客户端
    target_client = paramiko.SSHClient()
    target_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    target_client.connect(target_host, username=target_user, password=target_password, sock=jump_channel)

    # 使用 SCP 将文件从本地传输到目标服务器
    with SCPClient(target_client.get_transport()) as scp:
        scp.put(local_model_path, remote_path=remote_target_path, recursive=True)  # 递归上传文件夹

    print(f"文件已成功上传到 {target_host}:{remote_target_path}")

    # 执行远程脚本
    stdin, stdout, stderr = target_client.exec_command(f"bash {remote_target_path}run_script.sh")
    print("执行远程脚本...")

    # 打印脚本的输出
    print(stdout.read().decode())

    # 关闭连接
    target_client.close()
    jump_client.close()

# 调用传输和执行函数
transfer_file_via_jump_host()
